<template>
  <div id="userLoginView">
    <h1 style="margin-bottom: 20px">用户登录</h1>
    <a-form
      style="max-width: 480px; margin: 0 auto"
      label-align="left"
      auto-label-width
      :model="form"
      @submit="handleSubmit"
    >
      <a-form-item field="账号" tooltip="Please enter username" label="账号">
        <a-input
          v-model="form.userAccount"
          placeholder="请输入账号"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="密码" label="密码">
        <a-input-password
          allow-clear
          v-model="form.userPassword"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item
        field="验证码"
        tooltip="Please enter username"
        label="验证码"
        validate-trigger="blur"
      >
        <a-space size="large">
          <a-input
            v-model="form.captcha"
            style="height: 40px"
            placeholder="请输入验证码"
            allow-clear
          >
            <template #prefix>
              <icon-bold />
            </template>
          </a-input>
          <a-tooltip content="点击获取">
            <a-image
              style="cursor: pointer"
              alt="验证码"
              :src="captchaUrl"
              :preview="false"
              show-loader
              @click="getCaptcha"
            />
          </a-tooltip>
        </a-space>
      </a-form-item>
      <a-form-item
        style="display: flex; align-items: center; justify-content: right"
      >
        <a-button type="primary" html-type="submit" style="width: 120px"
          >登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { UserControllerService, UserLoginRequest } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const form = reactive({
  userAccount: "",
  userPassword: "",
  captcha: "",
} as UserLoginRequest);

const router = useRouter();
const store = useStore();

const handleSubmit = async () => {
  const res = await UserControllerService.userLoginUsingPost(form);
  if (res.code === 0) {
    await store.dispatch("user/getLoginUser");
    router.push({
      path: "/",
      replace: true,
    });
  } else {
    message.error("登录失败:" + res.message);
  }
};

const captchaUrl = ref("");

// 获取验证码
const getCaptcha = () => {
  captchaUrl.value =
    "http://localhost:8121/api/user/verifyCode?time=" + new Date();
};

onMounted(() => {
  getCaptcha();
});
</script>

<style scoped></style>
